<?php

/**
 * Abstract controller definition file
 *
 * @author coder_
 */

abstract class _Controller
{
    protected $Vars = array();
    private $patterns = array(
        '|<(\$)([^>]+)>|i',         # variables     - <$var_name>
        '|<(\|)([^>]+)>|i',         # constants     - <|const>
        '|<(\+)([^>]+)>|i',         # views           - <+view_name>
        '|<-(POST):([^>]+)>|i',     # post vars     - <-POST:var_name>
        '|<-(GET):([^>]+)>|i',      # get vars      - <-GET:var_name>
        '|<-(REQUEST):([^>]+)>|i',  # get vars      - <-REQUEST:var_name>
        '|<-(SERVER):([^>]+)>|i',   # server vars   - <-SERVER:var_name>
        '|<-(SESSION):([^>]+)>|i',  # session vars  - <-SESSION:var_name>
        '|<-(STYLE):([^>]+)>|i',    # style tag        - <-SCRIPT:url or uri>
        '|<-(SCRIPT):([^>]+)>|i'     # script tag       - <-STYLE:url or uri>
    );

    public function parseTemplate($template, $return = false)
    {
        $templateFile = VIEWS . '/' . $template . '.php';

        if(!file_exists($templateFile))
        {
            // TODO show 500 internal error page
            println('view not found');
            return;
        }

        $content = file_get_contents($templateFile);
        $this->parse($content);
        if($return)
            return $content;
        echo $content;
    }

    public function parseFile($path)
    {
        if(!file_exists($path))
        {
            // TODO show 500 internal error page
            println('required file not found');
            return;
        }

        $content = file_get_contents($path);
        $this->parse($content);
        file_put_contents(PROCESSED . '/' . pathinfo($path, PATHINFO_BASENAME), $content);
    }

    protected function getParameter($name)
    {
        return getModules()->Request->getParameter($name);
    }

    protected function getParameters()
    {
        return getModules()->Request->getParameters();
    }

    protected function respondJSON($data)
    {
        $data = json_encode($data);
        // TODO send data to core
    }

    protected function importHelper($name)
    {
        $helperFile = HELPERS . '/' . $name . '.php';
        if(!file_exists($helperFile))
        {
            // TODO show 500 internal error page
            println('helper not found');
        }

        include_once($helperFile);
    }

    private function parse(&$content)
    {
        extract((array)$this->Vars);
        ob_start();
        $content = preg_replace_callback($this->patterns, array($this, 'parseCallback'), $content);
        eval('?>' . $content);
        $content = ob_get_clean();
    }

    private function parseCallback($matches)
    {
        $result = '';
        $type = $matches[1];
        $string = $matches[2];

        switch($type)
        {
            case '$': // replace with variable
                    $result = isset($this->Vars[$string]) ? $this->Vars[$string] : '';
                break;
            case '|': // replace with constant
                    $result = defined($string) ? constant($string) : '';
                break;
            case '+': // replace with view
                    $result = $this->parseTemplate($string, true);
                break;
            case 'POST': // replace with post var
                    $result = isset($_POST[$string]) ? $_POST[$string] : '';
                break;
            case 'GET': // replace with get var
                    $result = isset($_GET[$string]) ? $_GET[$string] : '';
                break;
            case 'REQUEST': // replace with request var
                    $result = isset($_REQUEST[$string]) ? $_REQUEST[$string] : '';
                break;
            case 'SERVER': // replace with server var
                    $result = isset($_SERVER[$string]) ? $_SERVER[$string] : '';
                break;
            case 'SESSION': // replace with session var
                    $result = isset($_SESSION[$string]) ? $_SESSION[$string] : '';
                break;
            case 'STYLE': // replace with link tag rel=stylesheet
                    if(strpos($string, '/') == 0)
                    {
                        $this->parseFile(STYLES . $string);
                        $path = PROCESSED_URL . $string;
                    } else {
                        $path = $string;
                    }
                    $result = '<link rel="stylesheet" type="text/css" href="' . $path . '"/>';
                break;
            case 'SCRIPT': // replace with script tag
                    if(strpos($string, '/') == 0)
                    {
                        $this->parseFile(SCRIPTS . $string);
                        $path = PROCESSED_URL . $string;
                    } else {
                        $path = $string;
                    }
                    $result = '<script type="text/javascript" src="' . $path . '"></script>';
                break;
        }
        return $result;
    }
}